In this tutorial, we will learn how to get the width and height of elements using
Vue.js. We will provide two examples. In the first example, we will utilize Vue 3 Composition API, ref, and getBoundingClientRect(). In the second example, we will use the Options API along with offsetWidth and offsetHeight to retrieve the width and height of elements.
Example 1 : Use Vue 3 to Get Element width and Height
In this example, we use the Composition API to obtain the width and height of an element by using `ref` and `.getBoundingClientRect()`.
Vue 3 Get Element Height and Width (Composition Api)
<script type="module">
const { createApp, ref,onMounted} = Vue
createApp({
setup() {
const elementRef = ref(null);
const elementWidth = ref(0);
const elementHeight = ref(0);
const getElementDimensions = () => {
if (elementRef.value) {
const {width,height} = elementRef.value.getBoundingClientRect();
elementWidth.value = width;
elementHeight.value = height;
}
};
onMounted(() => {
getElementDimensions();
});
return {
elementRef,
elementWidth,
elementHeight,
};
}
}).mount('#app')
</script>
Example 2: By using Vue Options Api to Get Element Width and Height
This is the second example of this tutorial. We use the Options API to get the element’s width and height by using offsetHeight and offsetWidth.
Vue Get Div Height and Width (Options Api)
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
height: '',
width: ''
}
},
mounted() {
const element = this.$refs.myElement
this.width = element.offsetWidth
this.height = element.offsetHeight
}
});
</script>